﻿#region << 版 本 注 释 >>
/*----------------------------------------------------------------
 * 修改人：
 * 时间：
 * 修改说明：
 *----------------------------------------------------------------*/
#endregion << 版 本 注 释 >>using System;
using Dapper;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using seejee_Backendium.Core.Interfaces;
using seejee_Backendium.Core.Models;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;

namespace seejee_Backendium.Data.Services
{
    public class BIPermissionsService:IBIPermissionsService
    {
        private readonly string _connectionString;
        private readonly ILogger<BIPermissionsService> _logger;

        public BIPermissionsService(IConfiguration config, ILogger<BIPermissionsService> logger)
        {
            _connectionString = config.GetConnectionString("Default");
            _logger = logger;
        }

        public async Task<IEnumerable<BIQuanXianAllDto>> GetAllAsync()
        {
            // SQL查询语句：获取客户名称和BI权限字段
            string sql = "select cOperatorName, iOperatorPermissions,iCusBIPermissions,iCusDBPermissions from SEBI_Operator;";

            // 创建数据库连接
            using var connection = new SqlConnection(_connectionString);

            try
            {
                // 打开数据库连接
                await connection.OpenAsync();

                // 执行查询并将结果映射为BIQuanXianDto对象
                var result = await connection.QueryAsync<BIQuanXianAllDto>(
                    sql,
                    commandType: CommandType.Text
                );

                // 返回查询结果
                return result ?? Enumerable.Empty<BIQuanXianAllDto>();
            }
            catch (SqlException ex)
            {
                // 捕获数据库相关异常（如连接失败、SQL错误等）
                throw new Exception("获取BI权限数据时发生数据库错误", ex);
            }
            catch (Exception ex)
            {
                // 捕获其他异常
                throw new Exception("获取BI权限数据失败", ex);
            }
        }
        public async Task<IEnumerable<BIQuanXianDto>> GetBIPerm(string cOperatorName)
        {
            // SQL查询语句：获取客户名称和BI权限字段
            string sql = "select cOperatorName, iCusBIPermissions from SEBI_Operator where cOperatorName=@cOperatorName;";

            // 创建数据库连接
            using var connection = new SqlConnection(_connectionString);
            try
            {
                // 打开数据库连接
                await connection.OpenAsync();

                // 执行查询并将结果映射为BIQuanXianDto对象
                var result = await connection.QueryAsync<BIQuanXianDto>(
                    sql,
                     new { cOperatorName = cOperatorName },  // 参数化传递
                    commandType: CommandType.Text
                );

                // 返回查询结果
                return result ?? Enumerable.Empty<BIQuanXianDto>();
            }
            catch (SqlException ex)
            {
                // 捕获数据库相关异常（如连接失败、SQL错误等）
                throw new Exception("获取BI权限数据时发生数据库错误", ex);
            }
            catch (Exception ex)
            {
                // 捕获其他异常
                throw new Exception("获取BI权限数据失败", ex);
            }
        }

        // 获取一级菜单（SEBI_MenuConfig）
        public async Task<IEnumerable<PrimaryMenuDto>> GetPrimaryMenusAsync()
        {
            string sql = "select id, cMenuName from SEBI_MenuConfig order by sort;";
            using var connection = new SqlConnection(_connectionString);
            await connection.OpenAsync();
            return await connection.QueryAsync<PrimaryMenuDto>(sql) ?? Enumerable.Empty<PrimaryMenuDto>();
        }

        // 获取二级菜单（SEBI_MenuConfig_1）
        public async Task<IEnumerable<SecondaryMenuDto>> GetSecondaryMenusAsync()
        {
            string sql = "select id, iMenu_id, cPerspectiveName from SEBI_MenuConfig_1;";
            using var connection = new SqlConnection(_connectionString);
            await connection.OpenAsync();
            return await connection.QueryAsync<SecondaryMenuDto>(sql) ?? Enumerable.Empty<SecondaryMenuDto>();
        }
        // 更新客户BI权限（保存到iCusBIPermissions）
        public async Task<BIQuanXianDto> UpdateAsync(BIQuanXianDto bIqx)
        {
            if (string.IsNullOrEmpty(bIqx.cOperatorName))
                throw new ArgumentException("客户名称不能为空");

            // SQL：根据客户名称更新权限字段
            string sql = @"
            update SEBI_Operator 
            set iCusBIPermissions = @iCusBIPermissions 
            where cOperatorName = @cOperatorName;";

            using var connection = new SqlConnection(_connectionString);
            await connection.OpenAsync();
            int affectedRows = await connection.ExecuteAsync(sql, new
            {
                iCusBIPermissions = bIqx.iCusBIPermissions,
                cOperatorName = bIqx.cOperatorName
            });

            if (affectedRows == 0)
                throw new KeyNotFoundException("未找到对应的客户");

            return bIqx;
        }
        public async Task<BIDBpermissions> UpdataBIPermissionsAsync(BIDBpermissions bIdbqx)
        {
            if (string.IsNullOrEmpty(bIdbqx.cOperatorName))
                throw new ArgumentException("客户名称不能为空");

            // SQL：根据客户名称更新权限字段
            string sql = @"
            update SEBI_Operator 
            set iCusDBPermissions = @iCusDBPermissions 
            where cOperatorName = @cOperatorName;";

            using var connection = new SqlConnection(_connectionString);
            await connection.OpenAsync();
            int affectedRows = await connection.ExecuteAsync(sql, new
            {
                iCusDBPermissions = bIdbqx.iCusDBPermissions,
                cOperatorName = bIdbqx.cOperatorName
            });

            if (affectedRows == 0)
                throw new KeyNotFoundException("未找到对应的客户");

            return bIdbqx;
        }
    }
}
